<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>购物车</title>
  <style>
    table {
      border-collapse: collapse;
    }
    thead {
      background-color: #f5f5f5;
    }
    th, td {
      border: 1px solid #aaa;
      padding: 8px 16px;
    }
    .active {
      background-color: aqua;
    }
  </style>
</head>
<body>

  <div id="app">
    <template v-if="books.length">
      <table>
        <thead>
          <tr>
            <th>序号</th>
            <th>书籍名称</th>
            <th>出版日期</th>
            <th>价格</th>
            <th>购买数量</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="book, index in books"
          :key="book.id"
          @click="rowClick(index)"
          :class="{ active: index == currentIndex }"
          >
            <td>{{ book.id }}</td>
            <td>{{ book.name }}</td>
            <td>{{ book.date }}</td>
            <td>{{ formatPrice(book.price) }}</td>
            <td>
              <button @click="increment(index, book)">-</button>
              {{ book.count }}
              <button @click="decrement(index, book)">+</button>
            </td>
            <td>
              <button @click="removeBook(index, book)">移除</button>
            </td>
          </tr>
        </tbody>
      </table>
      <h2>总价：{{ formatPrice(totalProce) }}</h2>
    </template>

  </div>
  
  <script src="../lib/vue.js"></script>
  <script src="./data/data.js"></script>
  <script>
    const app = Vue.createApp({
      data() {
        return {
          books:books,
          currentIndex: -1
        }
      },
      computed: {
        totalProce() {
          this.books.map((item) => {
            console.log(item.count * item.price)
          })
          return this.books.reduce((preValue, item) => {
            
            return preValue + item.count * item.price
          }, 0)
        }
      },
      methods: {
        decrement(index, book) {
          console.log(index,book)
          book.count++
        },
        increment(index, book) {
          book.count--
          if (book.count <= 0) {
            book.count = 0
          }
        },
        removeBook(index, book) {
          this.books.splice(index,1)
        },
        rowClick(index) {
          this.currentIndex = index
        },
        formatPrice(price) {
          return '¥' + price
        }
      }
    })
    app.mount("#app")
  </script>
</body>
</html>